package ln.javatest.day01.demo01;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

//事务操作
public class JDBCDemo08 {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pstat1 = null;
        PreparedStatement pstat2 = null;
        try {
            //1.获取连接
            //开启事务
            conn.setAutoCommit(false);
            conn = JDBCUtils.getConnection();
            //2.定义sql
            //2.1 张三 -500
            String sql1= "update account set balance= balance - ? where id = ?";
            //2.2 李四 +500
            String sql2= "update account set balance= balance + ? where id = ?";
            //3.获取执行sql对象
            pstat1 = conn.prepareStatement(sql1);
            pstat2 = conn.prepareStatement(sql2);
            //4.设置参数
            pstat1.setDouble(1,500);
            pstat1.setInt(2,1);

            pstat2.setDouble(1,500);
            pstat2.setInt(2,2);
            //5.执行sql
            pstat1.executeUpdate();
            //手动制造异常
            int i= 3/0;
            pstat2.executeUpdate();

            //提交事务
            conn.commit();
        } catch (SQLException throwables) {
            //事务回滚
            try {
                if(conn != null){
                    conn.rollback();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            throwables.printStackTrace();
        }finally {
            JDBCUtils.close(pstat1,conn);
            JDBCUtils.close(pstat2,null);
        }

    }
}
